package com.yuandian.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.management.entity.ConfProbeInterface;
import com.yuandian.api.management.entity.ConfProbeManage;
import com.yuandian.management.enums.AppIdEnum;
import com.yuandian.management.enums.CodeEnum;
import com.yuandian.management.enums.ModuleEnum;
import com.yuandian.management.enums.OperTypeEnum;
import com.yuandian.management.mapper.ConfProbeInterfaceMapper;
import com.yuandian.management.service.ConfProbeInterfaceService;
import com.yuandian.management.service.ConfProbeManageService;
import com.yuandian.management.socket.ProbeSocketRequest;
import com.yuandian.management.socket.ProbeSocketResponse;
import com.yuandian.management.socket.client.DefaultSocketClient;
import com.yuandian.management.socket.client.SocketClient;
import com.yuandian.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 探针接口配置-Service实现
 * @author zfsn
 * @date 2023-4-17
 */
@Slf4j
@Service
public class ConfProbeInterfaceServiceImpl extends ServiceImpl<ConfProbeInterfaceMapper, ConfProbeInterface>
		implements ConfProbeInterfaceService {


	@Autowired
	private ConfProbeInterfaceMapper confProbeInterfaceMapper;

	@Lazy
	@Autowired
	private ConfProbeManageService confProbeManageService;
	/**
	 * @param probeId
	 * @param probeManageEo
	 */
	@Override
	public void checkInterfaceInfo(Integer probeId, ConfProbeManage probeManageEo) {
		List<ConfProbeInterface> interfaceInfoEos = confProbeInterfaceMapper.queryInterfaceInfoByProbeId(probeId);
		if (CollectionUtils.isEmpty(interfaceInfoEos)) {//如果原本就没有接口信息
			this.addInterfaceInfo(probeId, probeManageEo);
		} else {
			//如果存在先删除，然后重新插入
			log.info("[探针采集配置管理][探针接口列表]存在接口记录,先删除,再新增记录-probeId:{}", probeId);
			confProbeInterfaceMapper.deleteInterfaceInfoByProbeId(probeId);
			this.addInterfaceInfo(probeId, probeManageEo);
		}
	}

	@Override
	public void deleteInterfaceByIds(List<Integer> ids) {
		if (CollectionUtils.isNotEmpty(ids)) {
			confProbeInterfaceMapper.deleteInterfaceByIds(ids);
		}
	}

	/**
	 * 探针接口列表
	 *
	 * @param confProbeInterface
	 * @return
	 */
	@Override
	public Page<ConfProbeInterface> queryProbeInterface(ConfProbeInterface confProbeInterface) {
		// 获取探针运行详情
		Integer probeId = confProbeInterface.getId();
		if (null == probeId) {
			return null;
		}
		ConfProbeManage probeManageEo = confProbeManageService.getById(probeId);
		if (null != probeManageEo) {
			//先判断是否有interfaceInfo,如果没有，直接查
			this.checkInterfaceInfo(probeId, probeManageEo);
		}
		// 查询
		LambdaQueryWrapper<ConfProbeInterface> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(ConfProbeInterface::getProbeId, probeId);
		return super.page(new Page<>(confProbeInterface.getPageNum(), confProbeInterface.getPageSize()),queryWrapper);
	}

	/**
	 * .
	 * 添加新的接口信息
	 *
	 * @param probeId
	 * @param probeManageEo
	 */
	private void addInterfaceInfo(Integer probeId, ConfProbeManage probeManageEo) {
		String ip = probeManageEo.getIp();
		SocketClient socketClient = new DefaultSocketClient(AppIdEnum.getAppIdEnumValue("0"), ModuleEnum.getModuleIdEnumValue("2"), Integer.parseInt(OperTypeEnum.getOperTypeEnumValue("6")));
		DefaultSocketClient.proTimeOut = 5;
		try {
			ProbeSocketResponse<String> psr = socketClient.execute(new ProbeSocketRequest(1, "", new ArrayList<>()), ip);
			if (psr != null && psr.getResult() != null) {
				if (psr.getResult().getCode().equals(CodeEnum.getOperTypeEnumValue("27"))) {
					List<String> prsk = psr.getDataList();
					log.info("探针ip:" + ip + ",--获取探针接口信息成功--返回码:" + psr.getResult() + "接口信息:" + prsk);
					List<ConfProbeInterface> list = new ArrayList<>();
					if (!CollectionUtils.isEmpty(prsk)) {
						for (String proInterface : prsk) {
							String[] captureInterface = proInterface.split("\\|");
							ConfProbeInterface info = new ConfProbeInterface();
							info.setInterfaceName(captureInterface[0]);
							info.setAlias(captureInterface[1]);
							if (!StringUtils.isEmpty(captureInterface[2])) {
								info.setNumber(Integer.parseInt(captureInterface[2]));
							}
							if (!StringUtils.isEmpty(captureInterface[3])) {
								info.setSpeed(Integer.parseInt(captureInterface[3]));
							}
							info.setActive(captureInterface[4].equals("true") ? 1 : 0);
							info.setProbeId(probeId);
							list.add(info);
						}
					}
					if (CollectionUtils.isNotEmpty(list)) {
						confProbeInterfaceMapper.addInterfaceInfo(list);
					}
				} else {
					log.error("探针ip:" + ip + "--获取对应接口信息失败!--返回码:" + psr.getResult());
				}
			}
		} catch (Exception e) {
			log.error("添加探针对应接口信息失败...", e);
		}
	}
}
